// pages/dynamic/dynamic.js
let axios = require("../../utils/util.js")
const app = getApp()
const myaudio = wx.createInnerAudioContext() //音频
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isStart: null, //播放下标
    iscur: false, //播放状态
    tolist: {}, //回复评论人一级
    tolist2: {}, //回复评论人二级
    content: '', //文本类容
    bottomHeight: 0, //定义comment容器与page容器下边界之间的距离
    active: 0,
    Details: {}, //详情
    placeholder: '输入评论…',
    options: [{
        name: '微信',
        icon: 'wechat',
        openType: 'share'
      },
      {
        name: '朋友圈',
        icon: 'wechat-moments',
        description: "右上角分享到朋友圈"
      },
    ],
    showShare: false, //分享面板
    dy_userId: '', //当前选中人id
    recordId: '', //动态id
    user_list: {}, //我的信息
    reportshow: false, //举报动态popup
    page: 1,
    collectRoom_data: true, //下拉默认还有数据
    imgList: [], //图片预览全集
    voide_src: '',
    voice_model: false,
    show: false,
    poabsolute: 46,
    mesChangeNum: 1,
    messageTop: ["关注", "推荐", "精选"],
    tab_xinbie: false,
    cur_tab: 0,
    left_Gender: [{
        id: 0,
        icon: "https://img.xunyinjiaoyou.com/static/xiaochengxu/img_05/dynamicpage_icon_nannv_nor@2x.png",
        text: '全部'
      },
      {
        id: 1,
        icon: "https://img.xunyinjiaoyou.com/static/xiaochengxu/img_05/dynamicpage_icon_nan_nor@2x.png",
        text: '男生'
      },
      {
        id: 2,
        icon: "https://img.xunyinjiaoyou.com/static/xiaochengxu/img_05/dynamicpage_icon_nv_nor@2x.png",
        text: '女生'
      },
    ],
    topList: [],
    recordList: [],
  },
  addcomment(data) {
    let tolist = data.currentTarget.dataset.tolist;
    let tolist2 = data.currentTarget.dataset.tolist2;
    // console.log(tolist);
    this.setData({
      tolist: tolist,
      tolist2: tolist2,
      placeholder: '回复 ' + tolist2.nickname ? tolist2.nickname : tolist.nickname
    })

  },

  // 获取焦点 唤起软键盘
  bindfocus(e) {
    // console.log('键盘弹起')
    // console.log(e, '键盘弹起')
    this.setData({
      bottomHeight: e.detail.height //将键盘的高度设置为comment容器与page容器下边界之间的距离。
    })

  },
  // 输入内容
  bindinput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  // 失去焦点 
  bindblur(e) {
    // console.log('收起键盘')
    // console.log(e, '收起键盘')
    this.setData({
      bottomHeight: 0
    })
  },

  onPageScroll(e) {
    let userid = 'tolist.userId';
    let userid2 = 'tolist2.userId';
    let id = 'tolist.id';
    let id2 = 'tolist2.id';
    this.setData({
      [userid]: this.data.Details.userId,
      [userid2]: this.data.Details.userId,
      [id]: '0',
      [id2]: '0',
      placeholder: '输入评论…',
    })
  },
  //删除评论
  delcomment(data) {
    let commentid = data.currentTarget.dataset.commentid[0];
    let index = data.currentTarget.dataset.commentid[1];
    let i = data.currentTarget.dataset.commentid[2];
    let params = {
      commentId: commentid
    };
    axios.axios({
      url: "/record/delComment",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        // console.log(typeof (i));
        if (typeof (i) == 'number') { //删除二级评论
          this.data.Details.commentList[index].treeComment.splice(i, 1)
          let commentList = "Details.commentList[" + index + "]"
          this.setData({
            [commentList]: this.data.Details.commentList[index]
          })
        } else { //删除一级评论
          let commentList = "Details.commentList"
          this.data.Details.commentList.splice(index, 1)
          this.setData({
            [commentList]: this.data.Details.commentList,
          })
        }
        let commentCount = 'Details.commentCount'; //评论数
        this.data.Details.commentCount--
        this.setData({
          [commentCount]: this.data.Details.commentCount
        })
      }
      wx.showToast({
        title: res.data.text,
        icon: "none",
        duration: 2000
      })
    })
  },
  //回车发送
  sendOut() {
    let params = {
      recordId: this.data.Details.recordId,
      content: this.data.content,
      toUserId: this.data.tolist2.userId?this.data.tolist2.userId:'',
      toCommentId: this.data.tolist.id,
    };
    axios.axios({
      url: "/record/addComment",
      data: params
    }).then(async (res) => {
      if (res.data.status == 0) {
        // console.log(res.data.result);
        let index_ = await this.callbackIndex(this.data.Details.commentList, res.data.result.to_comment_id ? res.data.result.to_comment_id : res.data.result.id);
        if (typeof (index_) == 'number') {
          let lat = 'Details.commentList[' + index_ + ']';
          this.setData({
            content: '',
            [lat]: res.data.result
          })
        } else { //1级评论
          let lat = 'Details.commentList';
          this.setData({
            content: '',
            [lat]: [res.data.result, ...this.data.Details.commentList]
          })
        }
        let commentCount = 'Details.commentCount'; //评论数
        this.data.Details.commentCount++
        this.setData({ 
          [commentCount]: this.data.Details.commentCount
        })
      }
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000,
      })

    })
  },
  //数组中是否有某个值
  callbackIndex(arr, item) {
    for (var i = 0; i < arr.length; i++) {
      // console.log(arr[i].id);
      // console.log(item);
      // console.log('-------------------------------------------');
      if (arr[i].id == item) {
        return i; //不支持则进入循环,判断为真后输入
      }
    }
  },
  onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  //分享朋友圈和微信
  shar_model() {
    this.setData({
      showShare: true
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  // 动态点赞
  likeRecord(data) {
    let recordId = this.data.Details.recordId
    let params = {
      recordId: recordId
    };
    axios.axios({
      url: "/record/likeRecord",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        let isLiked = 'Details.isLiked'
        let likeList = 'Details.likeList'
        let likeCount = 'Details.likeCount'
        this.data.Details.isLiked == 0 ? this.setData({
          [isLiked]: 1
        }) : this.setData({
          [isLiked]: 0
        })
        this.setData({
          [likeList]: res.data.result.likeList,
          [likeCount]: res.data.result.likeList.length,
        })
      }
      wx.showToast({
        title: res.data.text,
        icon: "none",
        duration: 2000
      })
    })
  },
  // 动态评论点赞
  likeComment(data) {
    let recordId = data.currentTarget.dataset.recordid[0];
    let index = data.currentTarget.dataset.recordid[1];
    // console.log(recordId);
    // console.log(index);
    let params = {
      commentId: recordId
    };
    axios.axios({
      url: "/record/likeComment",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        res.data.result.type == 1 ? this.data.Details.commentList[index].likeCount++ : this.data.Details.commentList[index].likeCount--,
          this.setData({
            ['Details.commentList[' + index + '].isLiked']: res.data.result.type == 1 ? '1' : '0',
            ['Details.commentList[' + index + '].likeCount']: this.data.Details.commentList[index].likeCount
          })
        wx.showToast({
          title: res.data.text,
          icon: "none",
          duration: 2000
        })
      }
    })
  },
  onCloseShare() {
    this.setData({
      showShare: false
    })
  },

  onSelect(event) {
    // console.log(event);
  },
  onClickHide() {
    this.setData({
      tab_xinbie: false
    });
  },

  tab_xinbie_true() {
    this.setData({
      tab_xinbie: !this.data.tab_xinbie
    })
  },
  qie_cur_tab(data) {
    this.setData({
      cur_tab: data.currentTarget.dataset.index,
      tab_xinbie: false
    })
  },

  play_voice_click(data) {
    let voide_src = data.currentTarget.dataset.src;
    this.setData({
      voice_model: true,
      voide_src: voide_src,
    })
  },
  tuichu_play() {
    this.setData({
      voide_src: '',
      voice_model: false,
    })
  },
  // 放大背景图
  preview(event) {
    this.setData({
      imgList: []
    })
    event.currentTarget.dataset.src[0].forEach(item => {
      this.data.imgList.push(item);
    });
    let currentUrl = event.currentTarget.dataset.src[1]
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: this.data.imgList // 需要预览的图片http链接列表
    })
  },
  toReporting() {
    wx.showToast({
      title: '举报动态',
    })
    // wx.navigateTo({
    //   url: '/pages/me/me?memberId=' + data.currentTarget.dataset.perfectnumber,
    // })
  },
  // 删除动态
  delRecord() {
    let params = {
      recordId: this.data.recordId
    };
    axios.axios({
      url: "/record/delRecord",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let user_list = wx.getStorageSync('UserInformation')
    this.setData({
      user_list: user_list,
    })
    this.recordInfo(options.recordId)
    myaudio.onPlay(() => { //开始播放
      console.log("开始的回调");
    })
    myaudio.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
      that.setData({
        isStart: null
      })
    })
    myaudio.onEnded((res) => { //结束播放
      console.log("结束的回调");
      that.setData({
        isStart: null,
        iscur: false
      })
      // myaudio.stop()
    })
  },
  recordInfo(recordId) {
    let params = {
      recordId: recordId
    };
    axios.axios({
      url: "/record/recordInfo",
      data: params
    }).then((res) => {
      if (res.data.result.picUrl) {
        res.data.result.picUrl = res.data.result.picUrl.split(';');
      }
      let userid = 'tolist.userId';
      let id = 'tolist.id';
      this.setData({
        Details: res.data.result,
        [userid]: res.data.result.userId,
        [id]: '0',
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  start(data) {
    let that = this;
    let e = data.currentTarget.dataset.start[0]; //播放地址
    that.setData({
      iscur: !this.data.iscur
    })
    if (that.data.iscur) { //播放中
      myaudio.src = e;
      myaudio.play(); //开始播放 
    } else { //暂停播放
      console.log("暂停");
      myaudio.pause()
    }
  },
  // 跳转个人主页
  tomemberId(data) {
    wx.navigateTo({
      url: '/pages/me/me?memberId=' + data.currentTarget.dataset.perfectnumber,
    })
  },
  call(data) {
    let recordId = data.currentTarget.dataset.recordid;
    console.log(recordId);
    let params = {
      recordId: recordId
    };
    axios.axios({
      url: "/record/call",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 3000
      })
    })
  },
  onClose() {
    this.setData({
      reportshow: false
    });
  },
  showpopup(data) {
    let dy_userId = data.currentTarget.dataset.userid[0];
    let recordId = data.currentTarget.dataset.userid[1];
    this.setData({
      reportshow: true,
      dy_userId: dy_userId,
      recordId: recordId
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
